package com.gitee.huxing.course.config;

import lombok.Builder;
import lombok.Data;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description: 数据库自动连接配置
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.config
 * @ClassName: DataSourceConfig
 * @Author: huxing
 * @DateTime: 2021-09-05 上午9:24
 */
@Data
@Profile("custom")
@Configuration
@ConfigurationProperties("spring.datasource")
public class DataSourceConfig {

    @Value("driver")
    public String driver;

    @Value("url")
    public String url;

    @Value("username")
    public String userName;

    @Value("password")
    public String password;

    @Bean("myDataSource")
    public DataSource connection() throws ClassNotFoundException, SQLException {
        // 加载驱动
        DriverManagerDataSource managerDataSource = new
                DriverManagerDataSource(url, userName, password);
        managerDataSource.setDriverClassName(driver);
        // 连接数据源
        managerDataSource.getConnection();
        return managerDataSource;
    }

    @Primary
    @Bean("myJdbcTemplate")
    public JdbcTemplate create(@Qualifier("myDataSource")DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }

    @Bean("myConnection")
    public Connection getConnection(@Qualifier("myDataSource")DataSource dataSource) throws SQLException{
        return dataSource.getConnection();
    }
}
